#include "lprintf.h"
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>

void* thread(void* arg)
{
     pthread_mutex_t* mutex = (pthread_mutex_t*) arg;
     puts("in thread");

     sleep(3);
     if(pthread_mutex_unlock(mutex))
     {
	  puts("unlock err");
	  exit(1);
     }
     
     puts("unlocked");
     return NULL;
}
int main()
{

     struct sockaddr_in add;
     add.sin_addr.s_addr = inet_addr("127.0.0.1");
     add.sin_port = htons(4001);
     add.sin_family = AF_INET;

     int sockfd = socket(AF_INET, SOCK_STREAM, 0);

     if (sockfd < 0)
     {
	  perror("socket");
	  return 0;
     }

     if (connect(sockfd,(struct sockaddr*) &add, sizeof(add)) < 0)
     {
	  perror("connect");
	  return 0;
     }

     char buf[BUFSIZ];

     int ret;
     ret = read(sockfd, buf, sizeof(buf));
     buf[ret] = 0;
     puts(buf);

     {
	  char msg[] = "USER root\r\n";
	  write(sockfd, msg, sizeof(msg) - 1);
     }

     ret = read(sockfd, buf, sizeof(buf));
     buf[ret] = 0;
     puts(buf);

     {
	  char msg[] = "PASS 123\r\n";
	  write(sockfd, msg, sizeof(msg) - 1);
     }
     

     ret = read(sockfd, buf, sizeof(buf));
     buf[ret] = 0;
     puts(buf);

     {
	  char msg[] = "PASV\r\n";
	  write(sockfd, msg, sizeof(msg) - 1);
     }
     
     ret = read(sockfd, buf, sizeof(buf));
     buf[ret] = 0;
     puts(buf);

     {
	  char msg[] = "list\r\n";
	  write(sockfd, msg, sizeof(msg) - 1);
     }
     
     ret = read(sockfd, buf, sizeof(buf));
     buf[ret] = 0;
     puts(buf);

     {
	  char msg[] = "QUIT\r\n";
	  write(sockfd, msg, sizeof(msg) - 1);
     }
     ret = read(sockfd, buf, sizeof(buf));
     buf[ret] = 0;
     puts(buf);

     return 0;
     
     puts("listen");
     
     pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;


     if((ret = pthread_mutex_lock(&mutex)))
     {
	  puts("mutx lock failed!");
	  printf("ret val: %d\n", ret);
	  exit(0);
     }

     pthread_t tid;
     pthread_create(&tid, NULL, thread, &mutex);
     puts("thread created");

     if(pthread_mutex_lock(&mutex))
     {
	  puts("lock err");
     }
     puts("lock again");
     
     pthread_detach(tid);

      
     return 0;
}
